import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 修改初始状态，包含 username
const initState = { 
  nickname: '', 
  avatar: '',
  username: '', 
  token: undefined 
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo & { token?: string, username?: string }>({ ...initState })

    const setUserInfo = (val: IUserInfo & { username?: string }) => {
      userInfo.value = val
    }

    const setToken = (token: string) => {
      userInfo.value.token = token
    }
    
    // 新增：设置 username
    const setUsername = (username: string) => {
      userInfo.value.username = username
    }
    
    const clearUserInfo = () => {
      userInfo.value = { ...initState } // 这会同时清除 token 和 username
    }
    
    const reset = () => {
      userInfo.value = { ...initState }
    }
    
    const isLogined = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
      setToken,
      setUsername, // 暴露新方法
      clearUserInfo,
      isLogined,
      reset,
    }
  },
  {
    persist: true,
  },
)